package com.ruoyi.web.controller.plant;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.plant.domain.Plant;
import com.ruoyi.plant.service.PlantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;


@Anonymous
    @Api(tags = "植物管理")
    @RestController
    public class PlantController {

        @Autowired
        PlantService plantService;
        @Autowired
        RedisCache cache;

        //查询植物列表
        @ApiOperation(value = "植物列表查询")
        @PostMapping("/GetPlantList")
        public AjaxResult GetPlantList(@RequestBody Plant p) {
            List<Plant> resultList = plantService.getPlantList(p);
            for (int i = 0; i < resultList.size(); i++) {
                String jsonStr = JSON.toJSONString(resultList.get(i));
                int id = resultList.get(i).getId();
                cache.setCacheObject(String.valueOf(id), jsonStr, 20, TimeUnit.SECONDS);
            }
            return AjaxResult.success(resultList);
        }

        //通过名字获取植物详情信息
        @ApiOperation(value = "获取植物详情")
        @ApiImplicitParam(name = "name", value = "植物名称", dataType = "string", dataTypeClass = String.class)
        @GetMapping("selectPlant")
        public AjaxResult selectPlant(@RequestParam(value = "name", required = false) String plantName) {
            List<Plant> selectPlant = plantService.selectPlant(plantName);
            return AjaxResult.success(selectPlant);
        }

        //新增植物
        @ApiOperation(value = "新增植物")
        @PostMapping("addPlant")
        public AjaxResult addPlant(@RequestBody Plant p){
            return AjaxResult.success(plantService.addPlant(p));
        }

        //修改植物
        @ApiOperation(value = "修改植物")
        @PutMapping("updatePlant")
        public AjaxResult updatePlant(@RequestBody Plant p){
            return AjaxResult.success(plantService.updatePlant(p));
        }

        //删除植物
        @ApiOperation("删除植物")
        @ApiImplicitParam(name = "id", value = "植物ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Long.class)
        @DeleteMapping("/{id}")
        public AjaxResult deletePlantById(@PathVariable int id) {
            return AjaxResult.success(plantService.deletePlantById(id));
        }

    //测试日志
    @ApiOperation("测试日志")
    @PostMapping("selectPlantList2")
   // @Log(title = "获取了植物列表",businessType = BusinessType.OTHER)
    public AjaxResult selectPlantList2(@RequestBody Plant p){
        return AjaxResult.success(plantService.selectPlantList2(p));
    }

    }
